<!-- 知识产权页面 -->
<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          :icon="Plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['kjy:application:add']"
          >新增奖项</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          :icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:application:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :header-row-style="{ height: '70px', color: 'black', 'font-size': '16px' }"
      :header-cell-style="{ 'background-color': '#f5f7fa' }"
      :row-style="{ height: '60px' }"
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="企业名称" align="center" prop="enterpriseName" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="合作类型" align="center" prop="collaborationType" />
      <el-table-column label="合作对象" align="partner" prop="partner"> </el-table-column>
      <el-table-column label="合同金额" align="partner" prop="contractAmount"> </el-table-column>
      <el-table-column label="合同时间" align="center" prop="contractSignDate"> </el-table-column>
      <el-table-column label="合同附件" align="partner" prop="collaborationFile">
        <template #default="scope">
          <a
            v-if="scope.row.collaborationFile !== null"
            :href="getFirstItem(scope.row.collaborationFile)"
            target="_blank"
            >{{ getFirstItem(scope.row.collaborationFile).split('/').pop() }}</a
          >
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="primary" :icon="Edit" link @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="danger" :icon="Delete" link @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div
      :style="{
        padding: '15px',
        'background-color': '#fff',
        display: 'flex',
        'justify-content': 'end',
      }"
    >
      <el-pagination
        background
        :total="total"
        layout="prev, pager, next"
        v-model:page-size="queryParams.size"
        v-model:current-page="queryParams.current"
        :change="getList"
      />
    </div>

    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="企业名" prop="enterpriseName">
          <el-input
            v-model="form.enterpriseName"
            placeholder="请输入企业名"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="form.projectName"
            placeholder="请输入项目名称"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="合作类型(横向)" prop="type1">
          <el-select v-model="form.type1" placeholder="请选择合作类型(横向)" clearable>
            <el-option
              v-for="(item, index) in types1"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictLabel"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作类型(纵向)" prop="type2">
          <el-select v-model="form.type2" placeholder="请选择合作类型(纵向)" clearable>
            <el-option
              v-for="(item, index) in types2"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictLabel"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作对象" prop="partner">
          <el-input
            v-model="form.partner"
            placeholder="请输入合作对象"
            clearable
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="合同金额" prop="contractAmount">
          <el-input-number v-model="form.contractAmount" placeholder="合同金额"></el-input-number>
        </el-form-item>
        <el-form-item label="合同签订时间" prop="contractSignDate">
          <el-date-picker
            v-model="form.contractSignDate"
            type="date"
            placeholder="请选择合同签订时间"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="合同附件" prop="collaborationFile">
          <el-upload
            :headers="headers"
            multiple
            :accept="['doc', 'docx', 'pdf', 'png', 'png', 'jpg', 'jpeg']"
            :on-success="HandleSuccess"
            action="api/file/upload"
            :limit="3"
            :file-list="FileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不超过5mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getMyCooperateList,
  getCooperateType,
  getCooperateType2,
  addInfo,
  updateInfo,
  delInfo,
} from '@/api/my-cooperate';
import { getToken } from '@/utils/storage';
import { ref, reactive, onMounted, watch } from 'vue';
import { Delete, Plus, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'; // 假设你使用的是 Element Plus

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const headers = ref({
  Authorization: getToken(),
});
const open = ref(false);
const queryParams = reactive({
  current: 1,
  size: 10,
  enterpriseName: null,
});
const form = ref({
  id: null,
  enterpriseName: '',
  projectName: '',
  type1: '',
  type2: '',
  collaborationType: '-',
  partner: '',
  contractAmount: 0,
  contractSignDate: '',
  collaborationFile: '',
  publishTime: '',
});
const rules = reactive({
  enterpriseName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  type1: [{ required: true, message: '合作类型(横向)不能为空', trigger: 'blur' }],
  type2: [{ required: true, message: '合作类型(纵向)不能为空', trigger: 'blur' }],
  collaborationType: [{ required: true, message: '合作类型不能为空', trigger: 'blur' }],
  partner: [{ required: true, message: '合作对象不能为空', trigger: 'blur' }],
  contractAmount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
  contractSignDate: [{ required: true, message: '合同签订时间不能为空', trigger: 'blur' }],
});
const tableData = ref([]);
const types1 = ref([]);
const types2 = ref([]);
const selectedItem = ref(null);
const searchText = ref(null);
const isLoading = ref(false);
const FileList = ref([]);

// 获取合作类型(横向)
const getCooperateTypeData = async () => {
  try {
    const response = await getCooperateType();
    types1.value = response.data;
  } catch (error) {
    console.error('Failed to fetch cooperate types (horizontal):', error);
  }
};

// 获取合作类型(纵向)
const getCooperateType2Data = async () => {
  try {
    const response = await getCooperateType2();
    types2.value = response.data;
  } catch (error) {
    console.error('Failed to fetch cooperate types (vertical):', error);
  }
};

// 查询合作列表
const getList = async () => {
  loading.value = true;
  try {
    const response = await getMyCooperateList(queryParams);
    console.log(response.data.records);
    tableData.value = response.data.records;
    total.value = response.data.total;
    queryParams.current = response.data.current;
  } finally {
    loading.value = false;
  }
};

// 获取第一个项
const getFirstItem = (item) => {
  if (item !== null && typeof item === 'string') {
    const items = item.split(',');
    return items.length > 0 ? items[0].trim() : item;
  }
  return item;
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    enterpriseName: '',
    projectName: '',
    type1: '',
    type2: '',
    collaborationType: '-',
    partner: '',
    contractAmount: 0,
    contractSignDate: '',
    collaborationFile: '',
    publishTime: '',
  };
  selectedItem.value = null;
  searchText.value = null;
  FileList.value = [];
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.current = 1; // 重置分页
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  reset();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 添加按钮操作
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加合作企业';
};

const HandleSuccess = (response) => {
  form.value.collaborationFile = response.data.url;
};

// 修改按钮操作
const handleUpdate = (row) => {
  reset();
  form.value = row;
  form.value.type1 = row.collaborationType.split('-')[0];
  form.value.type2 = row.collaborationType.split('-')[1];
  open.value = true;
  title.value = '修改合作企业';
};

// 提交按钮操作
const submitForm = () => {
  console.log(form.value);
  const isValid = validateForm();
  if (isValid) {
    form.value.collaborationType = form.value.type1 + '-' + form.value.type2;
    console.log(form.value);
    form.value.publishTime = new Date().toISOString();
    if (form.value.id != null) {
      updateInfo(form.value)
        .then(() => {
          ElMessage.success('修改成功');
          open.value = false;
          getList();
        })
        .catch((error) => console.error('更新失败:', error));
    } else {
      addInfo(form.value)
        .then(() => {
          ElMessage.success('新增成功');
          open.value = false;
          getList();
        })
        .catch((error) => console.error('添加失败:', error));
    }
  }
};

// 表单验证
const validateForm = () => {
  // 检查必填字段是否已填写
  if (!form.value.enterpriseName) {
    ElMessage.error('企业名称不能为空');
    return false;
  }
  if (!form.value.projectName) {
    ElMessage.error('项目名称不能为空');
    return false;
  }
  if (!form.value.type1) {
    ElMessage.error('合作类型(横向)不能为空');
    return false;
  }
  if (!form.value.type2) {
    ElMessage.error('合作类型(纵向)不能为空');
    return false;
  }
  if (!form.value.collaborationType) {
    ElMessage.error('合作类型不能为空');
    return false;
  }
  if (!form.value.partner) {
    ElMessage.error('合作对象不能为空');
    return false;
  }
  if (form.value.contractAmount === undefined || form.value.contractAmount === null || form.value.contractAmount < 0) {
    ElMessage.error('合同金额不能为空且必须大于等于0');
    return false;
  }
  if (!form.value.contractSignDate) {
    ElMessage.error('合同签订时间不能为空');
    return false;
  }
  return true;
};

// 删除按钮操作
const handleDelete = (row) => {
  const idsToDelete = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除选中数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      delInfo(idsToDelete)
        .then(() => {
          getList();
          ElMessage.success('删除成功');
        })
        .catch((error) => console.error('删除失败:', error));
    })
    .catch(() => {});
};

// 文件上传改变事件

// 分页变化
const handlePageChange = (currentPage) => {
  queryParams.current = currentPage;
  getList();
};

// 监听查询参数的变化，自动触发查询
watch(
  queryParams,
  () => {
    handleQuery();
  },
  { deep: true }
);

// 组件挂载时调用
onMounted(() => {
  getList();
  getCooperateTypeData();
  getCooperateType2Data();
});
</script>
<style>
.app-container {padding: 20px;
  width: 100%;background-color: #fff;
}
</style>
